﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Infrastructure;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.ComponentModel.DataAnnotations.Schema;
using Dapper;

namespace Microsoft.AspNet.Identity.Dapper
{
    public abstract class AbstractDAL<TEntity> where TEntity: Entity.BaseEntityObject
    {
        protected AbstractDAL()
        {
            var entityType = typeof(TEntity);
            var tableAttribute = entityType.GetCustomAttribute<TableAttribute>();
            this.TableName = tableAttribute != null ? tableAttribute.Name : entityType.Name;
            this.Scheme = "dbo";

        }

        public string Scheme { get; private set; }
        public string TableName { get; private set; }
        

        public virtual long Insert(TEntity entity)
        {
            try
            {
                using (var conn = GetConnection())
                {
                   return conn.Insert(entity, this.TableName);
                }
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public virtual long Update(TEntity entity,string Id)
        {
            var key = entity.GetEntityPrimary;
            using (var conn = GetConnection())
            {
                return conn.Update(entity, new { Id = Id }, this.TableName);
            }
        }

        public virtual TEntity GetOne(string Id)
        {
            using (var conn = GetConnection())
            {
                return  conn.QueryList<TEntity>(new { Id =Id}, this.TableName).SingleOrDefault();
            }
        }
        public virtual IEnumerable<TEntity> GetAll(dynamic where=null)
        {
            var whereObj = where as object;
          
            using (var conn = GetConnection())
            {
                return conn.QueryList<TEntity>(whereObj, this.TableName);
            }
        }
       

        protected IDbConnection GetConnection()
        {
            return new SqlConnection(ConfigSettings.ConnectionString);
        }
     
    }
     
}
